import mysql, { Connection, MysqlError } from 'mysql'
import { Response } from 'express'
import {commonResponse, ok, fail} from "./commonResponse";
import {IPromiseCommonResponse} from "../../global";

class MysqlServer {
    static mysqlClient: Connection | null = null
    // 连接mysql
    static connect() {
        this.mysqlClient = mysql.createConnection({
            host: process.env.NODE_BASE_URL,
            user: process.env.NODE_BASE_MYSQL_USER,
            password: process.env.NODE_BASE_MYSQL_PASSWORD,
            database: process.env.NODE_BASE_MYSQL_DATABASE
        })
        this.mysqlClient.connect((error: MysqlError) => {
            if (error) throw error
            console.log("mysql connect success")
        })
    }
    static sqlAsync<T, K = null>(sql: string, params?: K): Promise<T> {
        return new Promise((resolve, reject) => {
            if (!this.mysqlClient) this.connect();
            (this.mysqlClient as  Connection).query(sql, params, (error: MysqlError | null, result: T) => {
                error ? reject(error) : resolve(result);
                if (this.mysqlClient) {
                    (this.mysqlClient as  Connection).end()
                    this.mysqlClient = null
                }
            })
        })
    }

    static transaction = (res: Response, cb: () => void) => {
        if (!this.mysqlClient) this.connect();
        (this.mysqlClient as Connection).beginTransaction(async (error) => {
            if (error) { fail(res,{ msg: '异常' }) }
            try {
                await cb();
                this.connect();
                (this.mysqlClient as Connection).commit(err => {
                    if (err) {
                        return (this.mysqlClient as Connection).rollback(() => {
                            fail(res,{ msg: '异常' })
                        })
                    } else {
                        ok<{ msg: string }>(res,{ msg: '成功' });console.log('222222222')
                    }
                });
            } catch (e) {
                this.connect();
                return (this.mysqlClient as Connection).rollback(() => {
                    fail(res,{ msg: '异常' })
                })
            }
            if (this.mysqlClient) {
                (this.mysqlClient as  Connection).end()
                this.mysqlClient = null
            }
        });
    }
}

export default MysqlServer